#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>

int main(int argc, char const *argv[])
{
    int pipeTest[2];
    int iRet = pipe( pipeTest );
    if ( iRet == -1 )
    {
        perror( "fail pipe in 02_pipe.c");
        return -1;
    }

    pid_t pid = fork();
    if ( pid > 0 )            // 父进程负责写
    {
        close( pipeTest[0] ); // 父进程关闭读管道, 只保留写管道
        char strWriteBuff[] = "Hello inter process";
        iRet = write( pipeTest[1], strWriteBuff, sizeof(strWriteBuff) );
        if ( iRet == -1 ) 
        {
            perror( "fail write" );
            return -1;
        }
        printf( "Write #%d bytes to pipe\n", iRet );
        close( pipeTest[1] );
    }
    else if ( pid == 0 )      // 子进程负责读
    {
        close( pipeTest[1] ); // 子进程关闭写管道, 只保留读管道
        char strReadBuff[100] = {0};
        iRet = read( pipeTest[0], strReadBuff, sizeof(strReadBuff) );
        if ( iRet == -1 )
        {
            perror( "fail read" );
            return -1;
        }
        printf( "Read #%d bytes from pipe\n", iRet );
        close( pipeTest[0] );
    }
    else
    {
        perror( "fail fork in 02_pipe.c" );
        return -1;
    }
    return 0;
}



/*

涉及函数:
    pipe
    fork
    write
    read
    close

程序流程:

    pipe
    创建一个子进程
    父进程写入pipe
        写入pipe
        关闭pipe write
    子进程读取pipe
        读取pipe
        关闭pipe read

知识要点:
    1) 父进程和子进程各有有独立的 读通道 和 写通道.
    2) 为保证管道的方向单一性, 在各自的进程中, 只保留一个通道.
    
*/